var app = getApp();

var drawer = require("./drawer");

Component({
    "options": {
        styleIsolation: 'isolated'
    },
    properties: {
        template: {type: Object, value: {}},
        data: {type: Object, value: {}},
        width: {type: Number, value: 320},
        height: {type: Number, value: 320},
        params: {type: Object, value: null}
    },
    data: {
        finished: false
    },
    lifetimes: {
        attached: function () {
        },
        detached: function () {
            this.data.drawer.destroy();
        },
        ready: function () {
            var ctx = wx.createCanvasContext('designer', this);
            var that = this;
            console.log(this.data.data);
            this.data.drawer = new drawer.Drawer(ctx, {
                onFinish: function () {
                    wx.canvasToTempFilePath({
                        canvasId: "designer",
                        success(res) {
                            console.log(res.tempFilePath);
                            that.setData({
                                thumbnail: res.tempFilePath
                            });
                        },
                        fail(res) {
                            console.log(res);
                        }
                    }, that);
                }
            });
            this.data.card = new drawer.Card(this.data.template);
            var data = this.data.data;
            if(this.data.params != null) {
                for(var key in this.data.params) {
                    data[key] = this.data.params[key];
                }
            }
            this.data.card.applyData(data);
            return this.data.card.draw(this.data.drawer)
                .catch(console.error);
        },
        error: function (e) {
            console.log(e);
        }
    },
    methods: {
        close: function () {
            this.triggerEvent('close');
        }
    }
});
